//
//  MPTEditUserDataViewController.m
//  MPTHome
//
//  Created by haoliangwei on 14/11/17.
//  Copyright (c) 2014年 Jeakin. All rights reserved.
//

#import "MPTEditUserDataViewController.h"
#import "MPTLoginApp.h"
#import "MPTUser.h"
#import "MPTLoginUser.h"
#import "MPTValidObject.h"
#import "MPTRotateLoadingView.h"
#import <Masonry.h>


#define   SWIDTH     [UIScreen mainScreen].bounds.size.width
#define   SHEIGHT    [UIScreen mainScreen].bounds.size.height
#define   MoveHeight  SHEIGHT>480?SHEIGHT>568?0:100:180;

@interface MPTEditUserDataViewController ()<UITextFieldDelegate,UITextViewDelegate,UIGestureRecognizerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, assign) BOOL isChange;
@property (nonatomic, strong) UIImage *iconImage;
@property (nonatomic, assign) BOOL isEdit;
@property (nonatomic, assign) BOOL isChangeSex;
@property (nonatomic, assign) BOOL isChangeIcon;
@property (nonatomic, assign) BOOL hadButon;
@property (nonatomic, strong) MPTLoginUser *myModel;
@property (nonatomic, strong) UIView *bacView;

@property (nonatomic, assign) BOOL changeIconSuccess;
@property (nonatomic, assign) BOOL changeInfoSuccess;

@property (nonatomic, assign) BOOL requestIcon;
@property (nonatomic, assign) BOOL requestInfo;

@end

@implementation MPTEditUserDataViewController
@synthesize myModel;

- (void)viewDidLoad
{
    [super viewDidLoad];
        
    self.title = @"编辑个人资料";
    
    self.view.backgroundColor = [UIColor MPTBackgroundColor];
    myModel = [[MPTLoginUser alloc] init];
    
    if ([MPTLoginApp isLogin])
    {
        myModel = [MPTLoginApp loginUser];
    }
    
    [self initView];
    
    if ([self.signTextView.text length]>0)
    {
        self.hintLabel.hidden = YES;
        if (myModel.desc.length > 50)
        {
            myModel.desc = [self.signTextView.text substringToIndex:50];
        }
    }
    else
    {
        self.hintLabel.hidden = NO;
    }
    
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    UIBarButtonItem*barItem = self.navigationItem.leftBarButtonItem;
    if ([barItem.customView isKindOfClass:[UIView class]]) {
        CGRect originalRect = barItem.customView.frame;
        originalRect.origin.x = 5;
        originalRect.size.width = 24;
        barItem.customView.frame = originalRect;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    CGFloat y = IS_IOS7_OR_LATER?64:0;
    CGRect editRect = self.editView.frame;
    editRect.origin.y = y;
    self.editView.frame = editRect;
    
    [[self navigationController] setNavigationBarHidden:NO animated:NO];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    CGFloat y = IS_IOS7_OR_LATER?64:0;
    CGRect editRect = self.editView.frame;
    editRect.origin.y = y;
    self.editView.frame = editRect;
    
    
    //性别按钮的点击范围太小  在这加下
    UIButton *bButton = [UIButton buttonWithType:UIButtonTypeCustom];
    bButton.frame = CGRectMake(self.boyButton.frame.origin.x, self.boyButton.frame.origin.y, self.boyButton.frame.size.width+self.boyLabel.frame.size.width+10, self.boyButton.frame.size.height);
    bButton.backgroundColor = [UIColor clearColor];
    [bButton addTarget:self action:@selector(changeSexWithBoy) forControlEvents:UIControlEventTouchUpInside];
    [self.editSexView addSubview:bButton];
    
    
    UIButton *gButton = [UIButton buttonWithType:UIButtonTypeCustom];
    gButton.frame = CGRectMake(self.girlButton.frame.origin.x, self.girlButton.frame.origin.y, self.girlButton.frame.size.width+self.girlLabel.frame.size.width+10, self.girlButton.frame.size.height);
    gButton.backgroundColor = [UIColor clearColor];
    [gButton addTarget:self action:@selector(changeSexWithGirl) forControlEvents:UIControlEventTouchUpInside];
    [self.editSexView addSubview:gButton];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[self navigationController] setNavigationBarHidden:YES animated:NO];
}

- (void)initView
{
    CGRect rect = self.iconImageView.frame;
    self.iconImageView.layer.cornerRadius = rect.size.width/2;
    self.iconImageView.layer.masksToBounds = YES;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = self.iconView.frame;
    [self.editView addSubview:button];
    [button addTarget:self action:@selector(changeIcon:) forControlEvents:UIControlEventTouchUpInside];
    
    self.lineView.backgroundColor = [UIColor MPTSeparatorColor];
    [self.lineView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0.5);
    }];
    
    self.iconLabel.textColor = [UIColor MPTMainTextColor];
    self.nickLabel.textColor = [UIColor MPTMainTextColor];
    self.nickLabel.font = [UIFont MPTH3Font];
    
    self.sexLabel.textColor = [UIColor MPTMainTextColor];
    self.sexLabel.font = [UIFont MPTH3Font];
    
    self.signLabel.textColor = [UIColor MPTMainTextColor];
    self.signLabel.font = [UIFont MPTH3Font];
    
    self.boyLabel.font = [UIFont MPTH3Font];
    self.boyLabel.textColor = [UIColor MPTMainTextColor];
    
    self.girlLabel.textColor = [UIColor MPTMainTextColor];
    self.girlLabel.font = [UIFont MPTH3Font];
    
    
    [self.boyButton addTarget:self action:@selector(changeSexWithBoy) forControlEvents:UIControlEventTouchUpInside];
    [self.girlButton addTarget:self action:@selector(changeSexWithGirl) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.nickTextField.font = [UIFont MPTH3Font];
    self.nickTextField.textColor = [UIColor MPTMainTextColor];
    self.nickTextField.delegate = self;
    self.nickTextField.placeholder = @"请输入昵称";
    //修改textField提示文字颜色
    [self.nickTextField setValue:[UIColor MPTAssistColor] forKeyPath:@"_placeholderLabel.textColor"];
    
    self.signTextView.font = [UIFont MPTH3Font];
    self.signTextView.textColor = [UIColor MPTMainTextColor];
    self.signTextView.delegate = self;
    self.signTextView.returnKeyType = UIReturnKeyDone;
    
    self.hintLabel.backgroundColor = [UIColor clearColor];
    self.hintLabel.textColor = [UIColor MPTAssistColor];
    self.hintLabel.hidden = YES;
    
    
    [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:myModel.icon] placeholderImage:[UIImage imageNamed:@"MPTCommonAvatar"]];
    self.nickTextField.text = myModel.nick;
    self.boyButton.selected = [myModel.gender integerValue] == 1?YES:NO;
    self.girlButton.selected = [myModel.gender integerValue] == 0?YES:NO;
    self.signTextView.text = myModel.desc;
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(taped)];
    [self.view addGestureRecognizer:tap];
    tap.delegate = self;
}

- (void)taped
{
    [self.nickTextField resignFirstResponder];
    [self.signTextView resignFirstResponder];
}

- (void)addEditButton
{
    if (self.hadButon) {
        return;
    }
    if (self.isEdit || self.isChangeIcon || self.isChangeSex) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"完成" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor MPTMainTextColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor MPTLightYellowColor] forState:UIControlStateHighlighted];
        button.titleLabel.font = [UIFont MPTH2Font];
        button.frame = CGRectMake(0, 0, 35, 44);
        [button addTarget:self action:@selector(updateEditInfo) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
        self.hadButon = YES;
    }
}

- (void)updateEditInfo
{
    [self taped];
    
    NSMutableDictionary *editInfo = [[NSMutableDictionary alloc] init];
    
    self.nickTextField.text = [self.nickTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if([self.nickTextField.text isValidNickname]){
        [editInfo setObject:[self.nickTextField.text urlEncode] forKey:@"nick"];
        myModel.nick = self.nickTextField.text;
    }else{
        NSString *hint ;
        if([self.nickTextField.text lengthOfBytesUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)] <4){
            hint = @"昵称设置过短";
        }else if([self.nickTextField.text lengthOfBytesUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)] >30){
            hint = @"昵称设置过长";
        }else{
            hint = @"昵称不合法";
        }
        [MPTTips showTips:hint duration:2.0];
        return;
    }
    
    
    if ([self.signTextView.text length] <= 50){
        
        [editInfo setObject:[self.signTextView.text urlEncode] forKey:@"desc"];
        
        myModel.desc = self.signTextView.text;
    }else if([self.signTextView.text length] > 50) {
        //        self.signTextView.text = [self.signTextView.text substringToIndex:70];
        [MPTTips showTips:@"个性签名输入过长"  duration:2.0];
        return;
    }else{
        [MPTTips showTips:@"个性签名输入有误"  duration:2.0];
        return;
    }
    
    if (self.isChangeSex) {
        [editInfo setObject:myModel.gender forKey:@"gender"];
    }
    
    if (self.isChangeSex || self.isEdit) {
        self.changeIconSuccess = YES;
        self.requestIcon = YES;
        [self updateInfo:editInfo];
        [self addHudView];
    }else{
        self.requestInfo = YES;
        self.changeInfoSuccess = YES;
    }
    
    if (self.isChangeIcon) {
        [self changeIconWithImage:self.iconImage];
        [self addHudView];
    }
    
}

- (void)addHudView
{
    if (self.bacView) {
        return;
    }
    UIView *mainView = [UIApplication sharedApplication].keyWindow.rootViewController.view;
    self.bacView = [[UIView alloc] init];
    self.bacView.frame = mainView.bounds;
    [mainView addSubview:self.bacView];
    self.bacView.backgroundColor = [UIColor YXRGBAColorWithSameNum:0 a:0.0];
    
    MPTRotateLoadingView *rotateLoadingview = [[MPTRotateLoadingView alloc] initWithFrame:CGRectMake(0.0f, 0.0, 50.0f, 50.0f)];
    [rotateLoadingview startAnimating];
    MBProgressHUD *HUD  = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.center = CGPointMake(self.bacView.center.x, self.bacView.center.y);
    HUD.customView = rotateLoadingview;
    HUD.mode = MBProgressHUDModeCustomView;
    [self.bacView addSubview:HUD];
    
}

- (void)removeHudView
{
    if (self.bacView) {
        [self.bacView removeFromSuperview];
        self.bacView = nil;
    }
}

- (void)updateInfo:(NSDictionary *)info
{
    self.requestInfo = NO;
    __weak typeof(self) weakSelf = self;
    MPTHttpClient *httpClient = [MPTHttpClient sharedMPHTTPClient];
    
    [httpClient modifyUserInfo:info success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        __strong typeof(weakSelf)strongSelf = weakSelf;
        if (strongSelf) {
            if ([responseObject[@"status"] integerValue] == 200) {
                strongSelf.requestInfo = YES;
                strongSelf.changeInfoSuccess = YES;
                
                myModel.nick = getValidObjectFromDictionary(responseObject, @"nick");
                myModel.desc = getValidObjectFromDictionary(responseObject, @"desc");
                myModel.gender = getValidObjectFromDictionary(responseObject, @"gender");
                [myModel archiver];
                [self changeSucces:responseObject];
                
            }else{
                strongSelf.requestInfo = YES;
                self.changeInfoSuccess = NO;
                [self changeSucces:responseObject];
            }
            
        }
        /// 发送更新消息
        [[NSNotificationCenter defaultCenter] postNotificationName:@"MPTLIVE_RequestNotification" object:nil];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        self.requestInfo = YES;
    }];
    
}

- (void)changeIconWithImage:(UIImage *)image
{
    self.changeIconSuccess = NO;
    self.requestIcon = NO;
    __weak typeof(self) weakSelf = self;
    MPTHttpClient *httpClient = [MPTHttpClient sharedMPHTTPClient];
    
    [httpClient updataUserIncoWithImage:image success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        __strong typeof(weakSelf)strongSelf = weakSelf;
        if (strongSelf) {
            if([responseObject[@"status"] integerValue] == 200){
                strongSelf.changeIconSuccess = YES;
                strongSelf.requestIcon = YES;
                
                NSString *newIcon = [responseObject objectForKey:@"newIcon"];
                myModel.icon = newIcon;
                [myModel archiver];
                
                [self changeSucces:responseObject];
            }
        }else{
            strongSelf.requestIcon = YES;
            strongSelf.changeIconSuccess = NO;
        }
        
        /// 发送更新消息
        [[NSNotificationCenter defaultCenter] postNotificationName:@"MPTLIVE_RequestNotification" object:nil];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        self.requestIcon = YES;
    }];
    
}

- (void)changeSucces:(NSDictionary *)dict
{
    if (self.requestIcon && self.requestInfo) {
        [self removeHudView];
        
        if (!self.changeIconSuccess && !self.changeInfoSuccess) {
            [MPTTips showTips:@"修改失败" duration:1.0];
            return;
        }
        
        if (self.changeIconSuccess && self.changeInfoSuccess) {
            UIAlertView *alet = [[UIAlertView alloc] initWithTitle:@"" message:@"修改成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alet show];
        } else if(!self.changeIconSuccess){
            [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:myModel.icon] placeholderImage:[UIImage imageNamed:@""]];
            [MPTTips showTips:@"图像修改失败" duration:1.0];
            
        }else if (!self.changeInfoSuccess){
            if (dict[@"msg"]) {
                [MPTTips showTips:dict[@"msg"] duration:1.0];
            }else{
                [MPTTips showTips:@"信息修改失败" duration:1.0];
            }
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"KEditUserInfoSuccess" object:nil];
    }
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)changeIcon:(UIButton *)btn
{
    [self taped];
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照上传",@"手机相册上传", nil];
    [sheet showInView:[UIApplication sharedApplication].keyWindow];
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        if (![UIImagePickerController isCameraDeviceAvailable: UIImagePickerControllerCameraDeviceFront] && ![UIImagePickerController isCameraDeviceAvailable: UIImagePickerControllerCameraDeviceRear])
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"没找到摄像头"
                                                            message: @"必须需要摄像头"
                                                           delegate: self
                                                  cancelButtonTitle: @"确定"
                                                  otherButtonTitles: nil];
            [alert show];
            
        }else{
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            [self presentViewController:picker animated:YES completion:nil];
        }
        
    }else if(buttonIndex == 1){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    //裁剪图像
    UIImage *images = [self imageWithImage:image scaledToSize:CGSizeMake(480, 480)];
    [self.iconImageView setImage:image];
    self.iconImage = images;
    
    self.isChangeIcon = YES;
    [self addEditButton];
    [picker dismissModalViewControllerAnimated:YES];
}

- (void)changeSexWithBoy
{
    self.isChangeSex = YES;
    [self addEditButton];
    myModel.gender = [NSNumber numberWithInt:1];
    
    self.girlButton.selected = NO;
    self.boyButton.selected = YES;
}

- (void)changeSexWithGirl
{
    self.isChangeSex = YES;
    [self addEditButton];
    myModel.gender = [NSNumber numberWithInt:0];
    
    self.boyButton.selected = NO;
    self.girlButton.selected = YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.isEdit = YES;
    [self addEditButton];
}

//昵称输入限制
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
    if ([string isEqualToString:@"\n"])
    {
        return YES;
    }
    
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (self.nickTextField == textField)
    {
        if ([toBeString lengthOfBytesUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)] > 30) {
            textField.text = [toBeString substringToIndex:toBeString.length-1];
            return NO;
        }
    }
    
    return YES;
}

//个性签名输入限制
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if([text isEqualToString:@"\n"]){
        [textView endEditing:YES];
        return NO;
    }
    
    NSString * toBeString = [self.signTextView.text stringByReplacingCharactersInRange:range withString:text];
    
    if ([toBeString length] <= 50) {
        
        return YES;
    }else{
        //        self.signTextView.text = toBeString;
        self.signTextView.text = [toBeString substringToIndex:50];
        return NO;
    }
    
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    if(textView.text.length == 0){
        self.hintLabel.hidden = NO;
    }else{
        if (textView.text.length > 50) {
            self.signTextView.text = [self.signTextView.text substringToIndex:50];
        }
        self.hintLabel.hidden = YES;
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    self.isEdit = YES;
    [self addEditButton];
    
    CGRect rect = self.view.frame;
    rect.origin.y -= MoveHeight;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame = rect;
    } completion:^(BOOL finished) {
        self.isChange = YES;
    }];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if (self.isChange) {
        self.isChange = NO;
        CGRect rect = self.view.frame;
        rect.origin.y += MoveHeight;
        [UIView animateWithDuration:0.3 animations:^(){
            self.view.frame = rect;
        }];
    }
}

- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
